# -*- coding: utf-8 -*-
import hashlib
import json
from collections import OrderedDict

import requests
from django.conf import settings

from async import async_job
from common.channel.pay import check_channel_order
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError

_LOGGER = track_logging.getLogger(__name__)

APP_CONF = {
    '3240': {
        # 知付二二零 支付宝H5 3.2% dwc
        'API_KEY': 'e9IaA1uKkDS0EMAGBNE4PD7c67Vm3Q',
        'gateway': 'http://pay.2wxr.cn?format=json',
        'query_gateway': 'http://pay.2wxr.cn/get_order_staus_by_id',
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def _get_query_gateway(mch_id):
    return APP_CONF[mch_id]['query_gateway']


def _gen_sign(s):
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest().upper()
    return sign


def gen_query_sign(d, key):
    s = '{}{}{}'.format(
        d['order_number'], d['uid'], key
    )
    return _gen_sign(s)


def gen_notify_sign(d, key):
    s = '{}{}{}'.format(
        d['amount'], d['order_number'], key
    )
    _LOGGER.info("zhifupay notify sing: %s", s)
    return _gen_sign(s)


def gen_create_sign(d, key):
    s = '{}{}{}{}{}{}{}{}'.format(
        d['notify_url'], d['order_number'], d['order_uid'], d['qr_amount'], d['return_url'], d['type'], d['uid'], key
    )
    _LOGGER.info("zhifupay create sing: %s", s)
    return _gen_sign(s)


def _build_query_string(d):
    s = '?uid={}&order_number={}&key={}'.format(
        d['uid'], d['order_number'], d['key']
    )
    return s


def verify_notify_sign(params, key):
    sign = params['key']
    params.pop('key')
    calculated_sign = gen_notify_sign(params, key)
    if sign.lower() != calculated_sign.lower():
        _LOGGER.info("zhifupay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def _get_pay_type(service):
    if service == 'alipay':
        return '1'
    elif service == 'wechat':
        return '2'
    elif service == 'union':
        return '3'
    return '1'


def _get_device_ip(info):
    try:
        extra = json.loads(info['extra'])
    except:
        extra = {}
    user_info = extra.get('user_info', {})
    return user_info.get('device_ip') or '127.0.0.1'


def create_charge(pay, pay_amount, info):
    service = info.get('service')
    app_id = str(info['app_id'])
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('uid', app_id),
        ('qr_amount', '%.2f' % pay_amount),
        ('notify_url', '{}/pay/api/{}/zhifupay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
        ('return_url', '{}/pay/api/{}/zhifupay/{}/'.format(settings.NOTIFY_PREFIX, settings.RETURN_PATH, str(pay.id))),
        ('order_number', str(pay.id)),
        ('order_uid', pay.user_id),
        ('type', _get_pay_type(service)),
        ('acc_no', ''),
    ))
    parameter_dict['key'] = gen_create_sign(parameter_dict, api_key)
    _LOGGER.info("zhifupay create: %s, order_id is: %s", json.dumps(parameter_dict), parameter_dict['order_number'])
    headers = {"Content-type": "application/x-www-form-urlencoded"}
    response = requests.post(_get_gateway(app_id), data=parameter_dict, headers=headers, timeout=3)
    # response = requests.post(_get_gateway(app_id), data=parameter_dict, headers=headers, timeout=3, verify=False)
    return {'charge_info': json.loads(response.text)['data']['qr_code']}


# OK
def check_notify_sign(request, app_id):
    api_key = _get_api_key(app_id)
    data = dict(request.POST.iteritems())
    _LOGGER.info("zhifupay notify data: %s", data)
    verify_notify_sign(data, api_key)
    pay_id = data['order_number']
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s", data)
        raise ParamError('zhifupay event does not contain pay ID')

    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id  # 商户编号
    trade_status = ''
    trade_no = ''
    total_fee = float(pay.total_fee)
    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee,
    }

    check_channel_order(pay_id, total_fee, app_id)
    if data:
        _LOGGER.info('zhifupay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    """ 查询订单 """
    pay_id = pay_order.id
    api_key = _get_api_key(app_id)
    dct = OrderedDict((
        ('uid', str(app_id)),
        ('order_number', str(pay_id)),
    ))
    dct['key'] = gen_query_sign(dct, api_key)
    _LOGGER.info('zhifupay query data: %s, order_id is: %s', json.dumps(dct), dct['order_number'])
    url = _get_query_gateway(app_id) + _build_query_string(dct)
    _LOGGER.info("huifutongpay query url: %s", url)
    response = requests.get(url, timeout=3)
    _LOGGER.info('zhifupay query rsp: %s', response.text)
    data = json.loads(response.text)
    if response.status_code == 200:
        trade_status = str(data['data']['status'])
        total_fee = float(pay_order.total_fee)
        trade_no = pay_order.third_id
        extend = {
            'trade_status': trade_status,
            'trade_no': trade_no,
            'total_fee': total_fee
        }
        # 1待支付 2已支付 3支付失败
        if trade_status == '2':
            _LOGGER.info('zhifupay query order success, mch_id:%s pay_id:%s' % (pay_order.mch_id, pay_order.id))
            order_db.add_pay_success(pay_order.mch_id, pay_order.id, total_fee, trade_no, extend)
            async_job.notify_mch(pay_order.id)
    else:
        _LOGGER.warn('zhifupay data error, status_code: %s', response.status_code)
